﻿using System.ComponentModel.DataAnnotations;
using System.Reflection;
using K9Nano.Authorization;
using K9Nano.MultiTenancy;
using Microsoft.AspNetCore.Mvc.Controllers;

namespace K9Nano.AspNetCore.Extensions
{
    public static class ControllerExtensions
    {
        public static IApiResource ToApiResource(this ControllerActionDescriptor descriptor)
        {
            var multiTenancySide = EMultiTenancySides.Tenant;
            string displayName = null;
            string description = null;
            var multiTenancy = descriptor.MethodInfo.GetCustomAttribute<MultiTenancyAttribute>();
            if (multiTenancy != null)
            {
                multiTenancySide = multiTenancy.MultiTenancySide;
            }

            var display = descriptor.MethodInfo.GetCustomAttribute<DisplayAttribute>();
            if (display != null)
            {
                displayName = display.Name;
                description = display.Description;
            }

            return new ApiResource(descriptor.ControllerName,
                descriptor.ActionName,
                displayName,
                description,
                multiTenancySide);
        }
    }
}